<template>
  <div
    :class="className"
    :style="{ height: height, width: width }"
    ref="chartContainer"
  />
</template>

<script setup>
import * as echarts from "echarts";

// 使用 defineProps 定义 props
const props = defineProps({
  className: {
    type: String,
    default: "chart",
  },
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "300px",
  },
  title: {
    type: String,
    default: "",
  },
  data: {
    type: Object,
    default: {},
  },
});

const chartContainer = ref(null);
let chartInstance = null;

// 初始化图表的函数
function initChart() {
  if (chartContainer.value) {
    chartInstance = echarts.init(chartContainer.value, "macarons");

    chartInstance.setOption({
      title: {
        text: props.title,
        left: "center",
      },
      tooltip: {
        trigger: "item",
      },
      toolbox: {
        show: true,
        feature: {
          mark: { show: true },
          dataView: { show: true, readOnly: false },
          restore: { show: true },
          saveAsImage: { show: true },
        },
      },
      series: [
        {
          type: "pie",
          radius: "50%",
          data: props.data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    });
  }
}

/** 监听 props.data 变化并初始化 */
watch(
  () => props.data,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      initChart();
    }
  },
  { deep: true }
);

// 组件销毁前清理资源
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
});
</script>
